﻿using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using System.Threading.Tasks;

namespace BJYJ_Admin.Web.Core;

public class JwtHandler : AppAuthorizeHandler
{
    private readonly IMemoryCache _memoryCache= App.GetRequiredService<IMemoryCache>() ;

    /// <summary>
    /// 重写 Handler 添加自动刷新授权逻辑
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    // public override async Task HandleAsync(AuthorizationHandlerContext context)  // Furion 4.9.3 之前版本使用这个
    public override async Task HandleAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        // 自动刷新 token
        if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext()))
        {
            await AuthorizeHandleAsync(context);
        }
        else context.Fail();    // 授权失败
    }
    public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        // 账号处于封禁状态，授权失败
        if (context.User.FindFirst("ISENABLED")?.Value == "1")
        {
            context.Fail();
           return Task.FromResult(false); ;
        }
        //账号处于30分钟锁定状态，授权失败 
        var keyPasswordErrorTimes = $"sys_password_error_times:{context.User.FindFirst("USERNAME")?.Value}";
        var passwordErrorTimes = _memoryCache.Get<int>(keyPasswordErrorTimes);
        if (passwordErrorTimes > 4)
        {
            context.Fail();
            return Task.FromResult(false); ;
        }

        return Task.FromResult(true);
    }
}
